package com.mspbots.core;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.Callable;

/**
 * @author billb
 */
public abstract class AbstractBaseController<T extends BaseEntity, S extends DefaultBaseService<T>> {

    protected S service;

    @GetMapping
    public Callable all() {
        return () -> service.list();
    }

    @GetMapping("page")
    public Callable selectPage(Page<T> page, T queryParams) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>(queryParams);
        return () -> service.page(page, queryWrapper);
    }

    @GetMapping(path = "/list")
    public Callable selectList(T queryParams) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>(queryParams);
        return () -> service.list(queryWrapper);
    }

    @GetMapping(path = "/{id}/info")
    public Callable selectById(@PathVariable Long id) {
        return () -> service.getById(id);
    }

    @PostMapping
    public Callable insert(@RequestBody T entity) {
        return () -> {
            service.saveOrUpdate(entity);
            return entity;
        };
    }

    @PutMapping(path = "/{id}")
    public Callable update(@RequestBody T entity) {
        return () -> {
            service.updateById(entity);
            return entity;
        };
    }

    @DeleteMapping(value = "/{id}")
    public Callable delete(@PathVariable Long id) {
        return () -> service.removeById(id);
    }


    @Autowired(required = false)
    public void setService(S service) {
        this.service = service;
    }

}
